package cn.rocksolid.sport.assist.service.impl;

import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.rocksolid.sport.assist.config.ConfigConst;
import cn.rocksolid.sport.assist.config.SmsConfig;
import cn.rocksolid.sport.assist.entity.SmsEntity;
import cn.rocksolid.sport.assist.service.SmsService;
import cn.rocksolid.sport.assist.sms.AliYunSmsProvider;
import cn.rocksolid.sport.assist.sms.SmsProvider;
import cn.rocksolid.sport.common.Constant.SmsProviderType;
import cn.rocksolid.sport.common.error.RSE;
import cn.rocksolid.sport.common.error.RockSolidException;

@Service
public class SmsServiceImpl implements SmsService {

  private Map<SmsProviderType, Map<String, SmsProvider>> smsProviders;

  /**
   * Below is service providers initial method.
   */
  @Autowired
  public SmsServiceImpl(SmsConfig smsConfig) {
    Map<SmsProviderType, Map<String, Map<String, String>>> smsConfigs = smsConfig.getSmsConfigs();
    if (MapUtils.isNotEmpty(smsConfigs)) {
      smsProviders = new EnumMap<>(SmsProviderType.class);
      for (Map.Entry<SmsProviderType, Map<String, Map<String, String>>> typeOfSmsConfigs : smsConfigs.entrySet()) {
        if (SmsProviderType.ALIYUN == typeOfSmsConfigs.getKey()) {
          Map<String, SmsProvider> aliyunSmsProviders = new HashMap<>();
          for (Map.Entry<String, Map<String, String>> config : typeOfSmsConfigs.getValue().entrySet()) {
            aliyunSmsProviders.put(config.getKey(), new AliYunSmsProvider(config.getValue()));
          }
          smsProviders.put(SmsProviderType.ALIYUN, aliyunSmsProviders);
        } else {
          throw new RockSolidException(RSE.INVALID_SMSP_CONF);
        }
      }
    }
  }

  @Override
  public void sendSms(SmsEntity smsDto) {
    SmsProvider provider = null;
    if (null == smsProviders.get(SmsProviderType.ALIYUN)
        || null == (provider = smsProviders.get(SmsProviderType.ALIYUN).get(ConfigConst.DEFAULT_CONF))) {
      throw new RockSolidException(RSE.MISS_SMSP);
    }
    provider.sendSms(smsDto, "顽石信息");
  }
}
